package com.mall.order.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.mall.cart.service.CartService;
import com.mall.manager.pojo.TbItem;
import com.mall.manager.pojo.TbUser;
import com.mall.order.pojo.OrderInfo;
import com.mall.order.service.OrderService;
import com.mall.pojo.TaotaoResult;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Administrator
 */

@Controller
public class OrderController {

    @Reference
    private CartService cartService;

    @Reference(timeout = 10000000)
    private OrderService orderService;

    /**
     * 显示要加入订单的购物车列表信息
     * @param req
     * @param model
     * @return
     */
    @GetMapping("/order/order-cart")
    public String orderCart(HttpServletRequest req, Model model){
        //只有用户登录了才可以来到这里
        TbUser user = (TbUser) req.getAttribute("User");
        List<TbItem> items = cartService.showCart(user.getId());
        model.addAttribute("cartList",items);
        return "order-cart";
    }

    /**
     * 创建订单
     * @param orderInfo
     * @return
     */
    @PostMapping("/order/create")
    public String createOrder(OrderInfo orderInfo, HttpServletRequest req, Model model){
        TbUser user = (TbUser) req.getAttribute("User");
        //补全用户id
        orderInfo.setUserId(user.getId());
        //设置卖家昵称
        orderInfo.setBuyerNick(user.getUsername());

        //调用创建订单服务
        TaotaoResult taotaoResult = orderService.createOrder(orderInfo);
        //订单创建成功
        if (taotaoResult.getStatus() == 200){
            //清空购物车
            orderService.deleteAllCartItemsByUserId(user.getId());
        }

        //返回视图需要的信息
        model.addAttribute("orderId",taotaoResult.getData());
        model.addAttribute("payment",orderInfo.getPayment());

        return "success";
    }

}
